<?php
namespace app\controllers;

use app\models\CateRecorder;

class CateController extends BaseController{
    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['CateRecorder']['id']);
        if($id){
            $model = CateRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }
        }else{
            $model = new CateRecorder();
            $model->addtime = time();
        }
        $result = $model->add($post);
        return json_encode($result);
    }

    public function actionList(){
        $list = $this->get_cate_list();
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }

    public function get_cate_list($parent_id=0,$level=0,$str="--",$arr=[]){
        $list = CateRecorder::find()->where('parent_id=:id',[':id' => $parent_id])->orderBy('cate_order ASC')->asArray()->all();
        foreach($list as $k=>$v){
            $level = (!$parent_id)?0:++$level;
            $list[$k]['str']=(!$parent_id)?"":"|".str_repeat($str,$level);
            $list[$k]['thumb_pic'] = empty($v['thumb_pic'])?'':str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
            $arr[]=$list[$k];
            $arr=$this->get_cate_list($v['id'],$level,$str,$arr);
        }
        return $arr;
    }

    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = CateRecorder::find()->where('id=:id',[':id' => $id])->asArray()->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model['thumb_pic'] = str_replace("../",\Yii::$app->params['pic_url'],$model['thumb_pic']);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    public function actionDel(){
        $id = \Yii::$app->request->post('id');
        $model = CateRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        //是否存在下级
        $is_child = CateRecorder::find()->where('parent_id='.$model->id)->count();
        if($is_child){
            $result = ['result'=>0,'data'=>'存在下级分类，请先删除或转移下级分类'];
            return json_encode($result);
        }
        $model->delete();
        $result = ["result"=>1,"data"=>'操作成功'];
        return json_encode($result);
    }
}
